package com.gs.api.reptile.util;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author guoyunfei on 2021/9/20 14:22
 * @className HttpImageUtil
 * @description TODO
 * @Version 1.0
 */
public class HttpImageUtil {

    static {
        try {
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
        }
    }

    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        trustAllCerts[0] = new TrustAllManager();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private static class TrustAllManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
    }

    /**
     * 判断网络图片是否存在
     * posturl 图片地址链接
     */
    public static boolean isImagesTrue(String posturl) throws IOException {

        URL url = new URL(posturl);

        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();

        urlcon.setRequestMethod("POST");

        urlcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

        try {
            if (urlcon.getResponseCode() == HttpURLConnection.HTTP_OK) {

                System.out.println(HttpURLConnection.HTTP_OK + posturl + ":posted ok!");

                return true;

            } else {

                System.out.println(urlcon.getResponseCode() + posturl + ":Bad post...");

                return false;

            }
        }catch (Exception e){

        }
        return false;

    }

    public static void main(String[] args) throws Exception {

        HttpImageUtil.isImagesTrue("https://b-ssl.duitang.com/uploads/item/201603/05/20160305143255_2GmVu.thumb.700_0.jpeg");

    }
}
